package com.sunshine.wrongquestionset.activity.exercise

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Html
import android.view.Menu
import android.view.MenuItem
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import com.sunshine.wrongquestionset.utils.FamiliarityUtils
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_exercise.*
import kotlinx.android.synthetic.main.activity_exercise_score.*
import kotlinx.android.synthetic.main.activity_exercise_score.viewPager
import java.util.*
import kotlin.collections.HashMap

class ExerciseScoreActivity : BaseActivity() {

    private lateinit var viewModel: ExerciseViewModel
    private lateinit var adapter: ExerciseScoreFragmentAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_exercise_score)
        setTitle(getString(R.string.label_exercise_score))

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(ExerciseViewModel::class.java)
        adapter = ExerciseScoreFragmentAdapter(this, questionList)
        viewPager.adapter = adapter
    }

    /**
     * 设置当前滚动到的位置，用于点击题目标签跳转到那道题目
     */
    fun setViewPagerCurrentItem(position: Int) {
        viewPager.currentItem = position
    }

    /**
     * 通知判分情况更新
     */
    fun notifyCardFragmentDataSetChanged() {
        adapter.getExerciseScoreCardFragment().notifyDataSetChanged()
    }

    /**
     * 将做题记录保存到数据库中
     */
    private fun toSaveAnswer() {

            if (questionList != null) {
                exerciseScoreMap.entries.forEach {
                    val questionEntity = questionList!![it.value.positionId]

                    //更新题目
                    val newFamiliarity = FamiliarityUtils.upFamiliarity(questionEntity, it.value.myScore / it.value.totalScore)?.familiarity?:questionEntity.familiarity
//                    viewModel.updateFamiliarity(questionEntity.id, newFamiliarity)
                    questionEntity.familiarity = newFamiliarity
                    questionEntity.doCount++
                    questionEntity.lastTime = Date().time
                    //questionEntity.score = it.value.myScore
                    viewModel.updateQuestion(questionEntity)

                    //添加练习记录
                    //TODO 注意，这里的获取答案的方式可能会报错，但是比较方便，+1是因为答案页首页id是1
                    viewModel.insertWrongQuestion(questionEntity.id, it.value.myScore, questionEntity.score, getAnswerMap()[it.key + 1]?.resultPath ?: "")

                    //添加做题信息
                    viewModel.insertQuestionInfo(questionEntity.id, newFamiliarity)
                }
            }
            Toasty.success(this, getString(R.string.exercise_success)).show()
            finish()
    }

    /**
     * 返回键二次确认
     */
    private fun backWarning() {
        val builder = MaterialAlertDialogBuilder(this)
        builder.apply {
            setTitle(getString(R.string.warning_title))
            setMessage(Html.fromHtml(getString(R.string.back_warning)))
            setNegativeButton("返回") {_, _ ->
                finish()
            }
            setPositiveButton("继续判分") {_, _ ->}

        }
        builder.create().show()
    }

    override fun onBackPressed() {
        backWarning()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_exercise_score, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                backWarning()
            }
            R.id.to_save_answer -> {
                if (exerciseScoreMap.size < questionList?.size?:0) {
                    Snackbar.make(root, getString(R.string.has_not_score), Snackbar.LENGTH_SHORT).show()
                } else {
                    toSaveAnswer()
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        //释放问题列表
        questionList = null
        exerciseResultMap = HashMap()
        exerciseScoreMap = HashMap()
    }

    companion object {
        var exerciseTime: String = "未知"
        private var questionList: List<QuestionEntity>? = null

        /**
         * 练习结果Map
         * key   题目所在位置
         * value 题目答案信息
         */
        private var exerciseResultMap = HashMap<Int, ExerciseBean>()

        /**
         * 练习分数Map
         * key   题目所在位置
         * value 题目所得分数
         */
        private var exerciseScoreMap = HashMap<Int, ScoreBean>()

        /**
         * 一个静态方法
         * 用于设置要练习的题目，可能不是一个好的方法，但是比intent简单
         */
        fun setQuestionList(list: List<QuestionEntity>?) {
            questionList = list
        }

        fun getQuestionList(): List<QuestionEntity>? {
            return questionList
        }

        fun setAnswerMap(map: HashMap<Int, ExerciseBean>) {
            exerciseResultMap = map
        }

        fun getAnswerMap(): HashMap<Int, ExerciseBean> {
            return exerciseResultMap
        }

        fun addScore(position: Int, questionId: Int, score: Float, totalScore: Float) {
            exerciseScoreMap[position] = ScoreBean(position, questionId, score, totalScore)
        }

        fun removeScore(position: Int) {
            exerciseScoreMap.remove(position)
        }

        fun getScoreMap(): HashMap<Int, ScoreBean> {
            return exerciseScoreMap
        }
    }
}